package com.supor.aiot.util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.baseconfig.common.utils.ThreadUtils;
import com.supor.aiot.R;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.ui.activity.WebActivity;
import com.supor.aiot.common.utils.AnimationUtil;

import java.lang.ref.WeakReference;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: AuthPrivacyPop <br>
 * 作者: lei <br>
 * 日期: 2020/12/28 <br>
 */
public class AuthPrivacyPop {

    static PopupWindow popupWindow;
    Handler handler;
    private WeakReference<Activity> activityReference;
    AuthPrivacyCallback callback;

    private static volatile AuthPrivacyPop instance;
    private float alpha;
    int duration = 300;
    int sleepTime = duration / 100;

    boolean isCheck = false;
    int type = 0;
    // CheckBox cbPrivacy = null;
    Button btnNextStep;

    public static AuthPrivacyPop getInstance() {
        if (instance == null) {
            instance = new AuthPrivacyPop();
        }
        return instance;
    }

    private AuthPrivacyPop() {
    }

    public void setCallback(AuthPrivacyCallback callback) {
        this.callback = callback;
    }

    public void initPop(Activity activity) {
        activityReference = new WeakReference<>(activity);
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        popupWindow = new PopupWindow();
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_auth_privacy, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);//解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(false);//点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.privacy_popup_window_anim1);

        TextView tvRetry = view.findViewById(R.id.tv_retry);
        tvRetry.setOnClickListener(v -> dismissPop());
        // cbPrivacy = view.findViewById(R.id.cb_privacy);
        // ImageView imageView = view.findViewById(R.id.iv_close);
        // TextView tvPrivacyText = view.findViewById(R.id.tv_privacy_text);
        // 请您阅读完整版《用户服务协议》《隐私保护声明》
        // String tip = activity.getResources().getString(R.string.privacy_text);
        // SpannableString spannableString = new SpannableString(tip);
        // ClickableSpan clickableSpan0 = new ClickableSpan() {
        //     @Override
        //     public void onClick(View widget) {
        //         cbPrivacy.setChecked(!cbPrivacy.isChecked());
        //     }
        //
        //     @Override
        //     public void updateDrawState(@NonNull TextPaint ds) {
        //         ds.setUnderlineText(false);
        //     }
        // };
        // spannableString.setSpan(clickableSpan0, tip.indexOf("请您"), tip.indexOf(
        //         "请您") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // ClickableSpan clickableSpan1 = new ClickableSpan() {
        //     @Override
        //     public void onClick(View widget) {
        //         gotoPrivacy(activity, AppGlobalHost.getHost() + Constants.USERSERVERAGREE);
        //     }
        //
        //     @Override
        //     public void updateDrawState(@NonNull TextPaint ds) {
        //         ds.setUnderlineText(false);
        //     }
        // };
        // spannableString.setSpan(clickableSpan1, tip.indexOf("用户"), tip.indexOf(
        //         "用户") + 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // ClickableSpan clickableSpan2 = new ClickableSpan() {
        //     @Override
        //     public void onClick(View widget) {
        //         gotoPrivacy(activity,  AppGlobalHost.getHost() + Constants.USERPRIVACYAGREE);
        //     }
        //
        //     @Override
        //     public void updateDrawState(@NonNull TextPaint ds) {
        //         ds.setUnderlineText(false);
        //     }
        // };
        // spannableString.setSpan(clickableSpan2, tip.indexOf("隐私"), tip.indexOf("隐私") + 4,
        //         Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //
        // spannableString.setSpan(new ForegroundColorSpan(activity.getResources().getColor(R.color.colorPrimary)),
        //         tip.indexOf("用户") - 1, tip.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // tvPrivacyText.setText(spannableString);
        // tvPrivacyText.setHighlightColor(0x00000000);
        // tvPrivacyText.setMovementMethod(LinkMovementMethod.getInstance());
        // imageView.setOnClickListener(v -> popupWindow.dismiss());
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        btnNextStep = view.findViewById(R.id.btn_next_step);
        btnCancel.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        btnNextStep.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        // cbPrivacy.setOnCheckedChangeListener((buttonView, isChecked) -> {
        //     btnNextStep.setBackgroundResource(isChecked ? R.drawable.bg_next :
        //             R.drawable.bg_disable_for_click);
        //     btnNextStep.setTextColor(isChecked ?
        //             activity.getResources().getColor(R.color.bg_next_color) :
        //             activity.getResources().getColor(R.color.white));
        //     if (callback != null) {
        //         callback.onChecked(isChecked);
        //     }
        // });
        // cbPrivacy.setChecked(isCheck());
        btnCancel.setOnClickListener(v -> {
            if (callback != null) {
                callback.authAgree(false);
            }
        });
        btnNextStep.setOnClickListener(v -> {
            // if (!cbPrivacy.isChecked()) {
            //     // Toast.makeText(this, "Hello mPaaS!", Toast.LENGTH_SHORT).show();
            //     ToastUtils.getInstance().showCustomToast(activity.getResources().getString(R.string.privacy_disagree_toast));
            //     return;
            // }
            if (callback != null) {
                callback.authAgree(true);
            }
        });


        /**
         * 退出popupWindow时取消暗背景
         */
        popupWindow.setOnDismissListener(() -> {
            ThreadUtils.execute(() -> {
                while (alpha < 1f) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    alpha += 0.005f;
                    msg.obj = alpha;
                    handler.sendMessage(msg);
                }
            });
        });
    }

    private void gotoPrivacy(Activity activity, String url) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.Key.param_type, 1);
        bundle.putString(Constants.Key.param_url, url);
        intent.putExtras(bundle);
        intent.setClass(activity, WebActivity.class);
        activity.startActivity(intent);
    }

    public void showPop(Activity activity, View rootView) {
        if (popupWindow == null) {
            initPop(activity);
        }
        // cbPrivacy.setChecked(isCheck());
        // if (type == 0) {
        //     btnNextStep.setText(activity.getResources().getString(R.string.privacy_agree_1));
        // } else {
        //     btnNextStep.setText(activity.getResources().getString(R.string.common_basic_agree));
        // }
        popupWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    //根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                //每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isCheck() {
        return isCheck;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setCheck(boolean check) {
        isCheck = check;
    }

    public boolean isPopShow() {
        return popupWindow != null && popupWindow.isShowing();
    }

    public void dismissPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    public interface AuthPrivacyCallback {
        void authAgree(boolean agree);

        void onChecked(boolean isChecked);
    }
}
